package cn.com.cifi.mars.web.action.report;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

import cn.com.cifi.mars.bean.vo.signPlan.DmAnalyticalVo;
import cn.com.cifi.mars.bean.vo.signPlan.SignPlanVersionVo;
import cn.com.cifi.mars.common.base.BaseAction;
import cn.com.cifi.mars.common.bean.R;
import cn.com.cifi.mars.common.exception.MsgException;
import cn.com.cifi.mars.common.redis.RedisTemplateUtil;
import cn.com.cifi.mars.constant.CodeEnum;
import cn.com.cifi.mars.entity.DmDmPlanSignMonth;
import cn.com.cifi.mars.entity.DmDmPlanSignYear;
import cn.com.cifi.mars.mapper.mars.DmDmPlanSignMonthMapper;
import cn.com.cifi.mars.mapper.mars.DmDmPlanSignYearMapper;
import cn.com.cifi.mars.service.DmDmPlanSignMonthService;
import cn.com.cifi.mars.service.IdmUserService;
import cn.com.cifi.mars.service.SignPlanVersionService;
import cn.com.cifi.mars.util.DmAnalyticalTemplate;
import cn.com.cifi.mars.util.LocalDateTimeUtils;
import lombok.extern.slf4j.Slf4j;

/**
 *
 * @Description：供销综合分析报表实现
 * @author：JYX
 * @date：2020年4月24日
 */
@Slf4j
@RestController
public class AnalyticalReportController extends BaseAction implements IAnalyticalReportController {

    @Autowired
    private SignPlanVersionService signPlanVersionService;
    @Autowired
    private DmDmPlanSignMonthMapper dmDmPlanSignMonthMapper;
    @Autowired
    private DmDmPlanSignYearMapper dmDmPlanSignYearMapper;
    @Autowired
    private DmDmPlanSignMonthService dmDmPlanSignMonthService;
    @Autowired
    private IdmUserService idmUserService;
    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    /**
     * 供销存综合分析底表刷新
     * @param apiVersion
     * @param projectId
     * @param yearMonth
     * @return
     */
    @Override
    public R refreshdmAnalytical(String apiVersion, String projectId, String yearMonth) {

        Integer yearMonthInt = Integer.valueOf(yearMonth.replace("-",""));

        List<String> versionIdList = new ArrayList<>();
        switch (apiVersion){
            case "v1":
                //查询全部项目
                Set<String> projectIds = signPlanVersionService.selectProjectIdAll();
                //查询每个项目指定年月全盘最新的版本集合
                List<String> versionIds;
                for(String id : projectIds){
                    dmDmPlanSignMonthMapper.delBySnapshootYearMonth(yearMonthInt);
                    dmDmPlanSignYearMapper.delBySnapshootYearMonth(yearMonthInt);
                    versionIds = signPlanVersionService.getOverallSignVersionList(id,yearMonth);
                    if(CollectionUtils.isNotEmpty(versionIds)){
                        versionIdList.addAll(versionIds);
                    }
                }
                break;
            case "v2":
                dmDmPlanSignMonthMapper.delByProjectIdAndSnapshootYearMonth(projectId,yearMonthInt);
                dmDmPlanSignYearMapper.delByProjectIdAndSnapshootYearMonth(projectId,yearMonthInt);
                //查询项目指定年月全盘最新的版本集合
                versionIdList = signPlanVersionService.getOverallSignVersionList(projectId,yearMonth);
                if(CollectionUtils.isEmpty(versionIdList)){
                    break;
                }
                break;
        }
        //刷新项目数据
        if(CollectionUtils.isNotEmpty(versionIdList)){
            dmDmPlanSignMonthService.toSign(versionIdList,yearMonth);
        }
        return ok("刷新成功");
    }

    /**
     * 手动刷新指定时间供销分析表中项目层级及以下数据
     * @param apiVersion
     * @param time
     * @return
     */
    @Override
    public R refreshProjectDmAnalytical(String apiVersion, String time) {
        List<DmDmPlanSignMonth> monthSignAllList = new ArrayList<>();
        List<DmDmPlanSignYear> yearSignAllList = new ArrayList<>();

        switch (apiVersion){
            case "v1":
                //查询全部数据,
                monthSignAllList = dmDmPlanSignMonthMapper.selectAll();
                yearSignAllList = dmDmPlanSignYearMapper.selectAll();

                //历史时间列表
                Set<Integer> yearMonthList = yearSignAllList.stream().map(s -> s.getSnapshootYearMonth()).collect(Collectors.toSet());
                for (Integer yearMonthInt : yearMonthList){
                    //筛选历史月数据
                    List<DmDmPlanSignMonth> monthSignList = monthSignAllList.stream().filter(s -> s.getSnapshootYearMonth().equals(yearMonthInt)).collect(Collectors.toList());
                    List<DmDmPlanSignYear> yearSignList = yearSignAllList.stream().filter(s -> s.getSnapshootYearMonth().equals(yearMonthInt)).collect(Collectors.toList());
                    //筛选出项目类别
                    List<String> projectIdList = yearSignAllList.stream().map(s -> s.getProjectId()).collect(Collectors.toSet()).stream().collect(Collectors.toList());
                    //计算汇总供销存分析表中项目层级及以下数据
                    List<DmAnalyticalVo> projectBelowVoAllList = dmDmPlanSignMonthService.getProjectDmAnalyticalVo(monthSignList, yearSignList, projectIdList,yearMonthInt);
                    redisTemplateUtil.delete("dmAnalyticalExport"+yearMonthInt);
                    redisTemplateUtil.set("dmAnalyticalExport"+yearMonthInt,projectBelowVoAllList,60*60*24*31L);
                }
                break;
            case "v2":
                Integer yearMonthInt= Integer.valueOf(time.replace("-",""));
                String year= time.split("-")[0];
                //查询全部数据,
                monthSignAllList = dmDmPlanSignMonthMapper.selectByYear(yearMonthInt,year);
                yearSignAllList = dmDmPlanSignYearMapper.selectBySnapshootYearMonth(yearMonthInt);


                //筛选历史月数据
                List<DmDmPlanSignMonth> monthSignList = monthSignAllList.stream().filter(s -> s.getSnapshootYearMonth().equals(yearMonthInt)).collect(Collectors.toList());
                List<DmDmPlanSignYear> yearSignList = yearSignAllList.stream().filter(s -> s.getSnapshootYearMonth().equals(yearMonthInt)).collect(Collectors.toList());
                //筛选出项目类别
                List<String> projectIdList = yearSignAllList.stream().map(s -> s.getProjectId()).collect(Collectors.toSet()).stream().collect(Collectors.toList());
                //计算汇总供销存分析表中项目层级及以下数据
                List<DmAnalyticalVo> projectBelowVoAllList = dmDmPlanSignMonthService.getProjectDmAnalyticalVo(monthSignList, yearSignList, projectIdList,yearMonthInt);
                redisTemplateUtil.delete("dmAnalyticalExport"+yearMonthInt);
                redisTemplateUtil.set("dmAnalyticalExport"+yearMonthInt,projectBelowVoAllList,60*60*24*31L);
                break;
        }
        return ok();
    }


    /**
     * 供销存综合分析表在线查看
     * @param apiVersion
     * @param ofYearMonth 截止年月
     * @param year 历史年份
     * @return
     */
    @Override
    public R<SignPlanVersionVo> dmAnalytical(String apiVersion, String ofYearMonth, String year) {
        //查询用户权限项目id列表
        List<String> projectIdList = idmUserService.queryUserProjectPermissions(getOperator().getUsername());
        if(CollectionUtils.isEmpty(projectIdList)){
            throw new MsgException(CodeEnum.NOT_PROJECT_PERMISSIONS_ERROR);
        }
        //供销存综合分析表数据
        SignPlanVersionVo vo = dmDmPlanSignMonthService.getSignPlanVersionVo(projectIdList,ofYearMonth,year);
        return ok(vo);
    }

    /**
     * 供销存综合分析表导出
     * @param apiVersion
     * @param yearMonth
     * @return
     */
    @Override
    public  void dmAnalyticalExport(String apiVersion, HttpServletResponse response, String yearMonth) {
        List<String> projectIdList = idmUserService.queryUserProjectPermissions(getOperator().getUsername());
        //供销存综合分析表数据
        List<DmAnalyticalVo> voList = dmDmPlanSignMonthService.dmAnalyticalExport(projectIdList,yearMonth);
        //数据精度修改(套数、套均面积、面积保留两位小数,均价、金额取整)
        dmDmPlanSignMonthService.updateDmAnalyticalVoAccuracy(voList);

        String name = "供销综合分析表-截止"+yearMonth.replace("-","")+"-"+ LocalDateTimeUtils.formatTime(LocalDateTime.now(), "yyyyMMddHH");
        //报表导出
        DmAnalyticalTemplate overallSignPlanTemplate = new DmAnalyticalTemplate(voList);
        overallSignPlanTemplate.setSheetDate(name);
        overallSignPlanTemplate.appendRows(voList);
        try (OutputStream outputStream = response.getOutputStream()){
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(name.concat(".xlsx"), "utf-8"));
            overallSignPlanTemplate.write(outputStream);
            outputStream.flush();
        } catch (IOException e) {
            log.error("###### errorMsg: ", e);
        }
    }
    
    class ExportReport extends Thread{
    	List<DmAnalyticalVo> voList;
    	String name;
    	HttpServletResponse response;
		public ExportReport(List<DmAnalyticalVo> voList, String name,HttpServletResponse response) {
			super();
			this.voList = voList;
			this.name = name;
			this.response = response;
		}
		@Override
		public void run() {
			//报表导出
	        DmAnalyticalTemplate overallSignPlanTemplate = new DmAnalyticalTemplate(voList);
	        overallSignPlanTemplate.setSheetDate(name);
	        overallSignPlanTemplate.appendRows(voList);
	        
	        try (OutputStream outputStream = response.getOutputStream()){
	            response.setContentType("application/vnd.ms-excel");
	            response.setHeader("Content-Disposition", "attachment;filename="+ URLEncoder.encode(name.concat(".xlsx"), "utf-8"));
	            overallSignPlanTemplate.write(outputStream);
	            outputStream.flush();
	        } catch (IOException e) {
	            log.error("###### errorMsg: ", e);
	        }
		}
    }

}
